#!/usr/bin/env python
# -*- encoding=utf-8 -*-
'''
Created on 2017/9/28

@author: x00173555
'''


import requests
import re, sys, json, os


GERRIT_PROJECT = os.environ["GERRIT_PROJECT"]
GERRIT_BRANCH = os.environ["GERRIT_BRANCH"]
GERRIT_CHANGE_ID = os.environ["GERRIT_CHANGE_ID"]
GERRIT_CHANGE_NUMBER = os.environ["GERRIT_CHANGE_NUMBER"]

'''
GERRIT_PROJECT = 'euleros/third_party/open_source/kernelspace/linux-4.19'
GERRIT_BRANCH = 'next_kernel'
#GERRIT_CHANGE_ID = 'I6994749c42da94920f1ba10571a1216aa85f6240'
GERRIT_CHANGE_NUMBER = '57416'
'''


def getContent(url):
    #使用requests.get获取知乎首页的内容
    r = requests.get(url)
    #request.get().content是爬到的网页的全部内容
    return r.content

#获取_xsrf标签的值
def getXSRF(url):
    #获取知乎首页的内容
    content = getContent(url)
    #正则表达式的匹配模式
    pattern = re.compile('.*?<input type="hidden" name="_xsrf" value="(.*?)"/>.*?')
    #re.findall查找所有匹配的字符串
    match = re.findall(pattern, content)
    xsrf = match[0]
    #返回_xsrf的值
    return xsrf

#登录的主方法
def login():
    #post需要的表单数据，类型为字典
    login_data = {
            'password': 'EulerOS_123',
            'username': 'peuleros',
            'rememberme': 1,
    }
    #设置头信息
    headers_base = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',
        'Connection': 'keep-alive',
        'Host': 'dgggit09-rd.huawei.com',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36',
        'Referer': 'http://dgggit09-rd.huawei.com/#/c/18784/detail?O=50004',
        'X-Gerrit-Auth': 'aOGefdB1RPtvHqiLv - e4WjApAscWvvdO'
    }
    #使用seesion登录，这样的好处是可以在接下来的访问中可以保留登录信息
    session = requests.session()
    #登录的URL
    baseurl = "http://dgggit09-rd.huawei.com/login/%23%2Fq%2Fstatus%3Aopen"
    #requests 的session登录，以post方式，参数分别为url、headers、data
    content = session.post(baseurl, headers = headers_base, data = login_data)

    return session
    #再次使用session以get去访问知乎首页，一定要设置verify = False，否则会访问失败


def check_verify_result(session):
    headers = {
        'content-type': "application/json; charset=UTF-8",
        'authorization': "Basic cGV1bGVyb3NjaTpFdWxlck9TXzEyMw==",
        'cache-control': "no-cache"
    }

    a = session.get("http://dgggit09-rd.huawei.com/a/changes/?q=status:open+change:{0}&o=CURRENT_REVISION&o=CURRENT_COMMIT&o=MESSAGES".format(GERRIT_CHANGE_NUMBER), headers=headers)
    if a.status_code != 200:
        print("code:{0}\n{1}".format(a.status_code, a.text))
        sys.exit(1)

    i = json.loads(a.content.replace(')]}\'', ''))[0]
    #print i

    a = session.get(
        "http://dgggit09-rd.huawei.com/a/changes/{0}/reviewers".format(
            i['id']), headers=headers)
    if a.status_code != 200:
        print("code:{0}\n{1}".format(a.status_code, a.text))
        sys.exit(1)

    j = json.loads(a.content.replace(')]}\'', ''))
    print j
    for k in j:
        if 'approvals' in k.keys():
            if 'Verified' in k['approvals'].keys():
                verify_result = k['approvals']['Verified']
    print verify_result
    if verify_result == '-1':
        print("Error: verify === -1")
        sys.exit(1)
    elif verify_result == '+1':
        # 设置verify +1 review +2
        json_data_review = {"message": 'merge by auto',
                            "labels": {
                                "Code-Review": +2
                            }
                            }
        json_data_review = json.dumps(json_data_review)
        json_data_submit = {"wait_for_merge": 'true'}
        json_data_submit = json.dumps(json_data_submit)
        e = session.post(
            "http://dgggit09-rd.huawei.com/a/changes/{0}/revisions/{1}/review".format(i['id'], i['current_revision']),
            headers=headers, data=json_data_review)
        if e.status_code != 200:
            print("code:{0}\n{1}".format(e.status_code, e.text))
            sys.exit(1)
        # submit提交
        f = session.post(
            "http://dgggit09-rd.huawei.com/a/changes/{0}/submit".format(i['id']),
            headers=headers, data=json_data_submit)
        if f.status_code != 200:
            print("code:{0}\n{1}".format(f.status_code, f.text))
            sys.exit(1)
    else:
        print('Nothing to do')

    return True


if __name__ == '__main__':
    session = login()
    check_verify_result(session)

